package cn.zh.aspects;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.zh.annotations.LogOperation;
import cn.zh.entity.Admin;
import cn.zh.entity.LogInfoCopy;
import cn.zh.service.LogInfoService;
import cn.zh.utils.IpUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

@Component
@Aspect
public class LogAspects {
    @Resource
    private LogInfoService logInfoService;
    @Pointcut("@annotation(cn.zh.annotations.LogOperation)")
    public void point(){}
    //环绕通知实现操作日志的记录
    @Around("point()")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {


        //方法耗时
        long start = System.currentTimeMillis();
        Object proceed = joinPoint.proceed();
        long end = System.currentTimeMillis();
        Long timeConsuming= end-start;
        //方法参数
        Object[] args = joinPoint.getArgs();
        String params="";
        if (ObjectUtil.isNotEmpty(args)){
            params = JSONUtil.toJsonStr(args);
        }

        //操作类型  模块 Method
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogOperation annotation = method.getAnnotation(LogOperation.class);
        String model = annotation.model();
        String operationType = annotation.operation().getOperationType();

        //username url ip->request

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("admin");
        String username = admin.getUsername();
        String uri = request.getRequestURI();

        String ip = IpUtil.getIp(request);
        LogInfoCopy logInfoCopy=new LogInfoCopy();
        logInfoCopy.setIp(ip);
        logInfoCopy.setModel(model);
        logInfoCopy.setDescription(operationType);
        logInfoCopy.setTimeConsuming(timeConsuming);
        logInfoCopy.setUrl(uri);
        logInfoCopy.setUsername(username);
        logInfoCopy.setParams(params);
        logInfoService.addLogInfo(logInfoCopy);
        System.out.println("日志添加");


        return proceed;
    }
}
